package com.bjy.qa.service.manage.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.AopUtils;
import com.bjy.qa.dao.manage.ResourceDao;
import com.bjy.qa.entity.MyPage;
import com.bjy.qa.entity.ResponsePagingData;
import com.bjy.qa.service.manage.IResourceService;
import com.bjy.qa.util.SpringTool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@org.springframework.stereotype.Service
public class ResourceService extends ServiceImpl<ResourceDao, com.bjy.qa.entity.manage.Resource> implements IResourceService {
    @Resource
    ResourceDao resourceDao;

    @Override
    public ResponsePagingData list(MyPage<com.bjy.qa.entity.manage.Resource> myPage) {
        Page<com.bjy.qa.entity.manage.Resource> page = new Page(myPage.getPageNum(), myPage.getPageSize()); // 构造待查询 page 对象
        page.setOrders(myPage.getOrders()); // 设置排序字段

        // 构造待查询 QueryWrapper
        com.bjy.qa.entity.manage.Resource resource = myPage.getQuery();
        QueryWrapper<com.bjy.qa.entity.manage.Resource> queryWrapper = new QueryWrapper<>();
        if (resource != null) {
            if (StringUtils.isNotBlank(resource.getDesc())) {
                queryWrapper.like("`desc`", resource.getDesc());
            }
            if (StringUtils.isNotBlank(resource.getPath())) {
                queryWrapper.like("path", resource.getPath());
            }
        }

        page = resourceDao.selectPage(page, queryWrapper); // 按分页查询

        myPage.setTotalRecords(page.getTotal()); // 设置返回总记录数

        return new ResponsePagingData(myPage, page.getRecords());
    }

    @Override
    public List<com.bjy.qa.entity.manage.Resource> listAll() {
        // 构造待查询 QueryWrapper
        QueryWrapper<com.bjy.qa.entity.manage.Resource> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("`desc`");

        return resourceDao.selectList(queryWrapper); // 按分页查询
    }

    @Override
    public int delete(Long id) {
        // TODO: 2023/7/28 这里后续要判断一下是否使用，使用的不让删除 
//        // 删除 project 前，先判断是不是有用户关联了此 project
//        QueryWrapper<UserCompanyProject> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("project_id", id);
//        if (userCompanyProjectDao.selectCount(queryWrapper) > 0) {
//            throw new MyException("删除错误。已经有用户关联到此项目，请先删除关联关系！");
//        }

        return resourceDao.deleteById(id);
    }

    @Override
    public Boolean sync() {
        RequestMappingHandlerMapping requestMappingHandlerMapping = SpringTool.getApplicationContext().getBean("requestMappingHandlerMapping", RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
        Map<String, String> parentMap = new HashMap<>();

        map.forEach((key, value) ->{
            String beanName = value.getBean().toString();
            String parentResourceDesc = parentMap.getOrDefault(beanName, getParentResourceDesc(beanName, parentMap)) ;
            if (parentResourceDesc == null) {
                return;
            }

            processResource(parentResourceDesc, key, value);
        });

        return true;
    }

    /**
     * 获取父级资源描述（也就是 Controller 的 @Api 中的 tag）
     * @param beanName
     * @param parentMap
     * @return
     */
    private String getParentResourceDesc(String beanName, Map<String, String> parentMap) {
        Api api = SpringTool.getBean(beanName).getClass().getAnnotation(Api.class);
        if (api == null) {
            return null;
        }
        RequestMapping requestMapping = AopUtils.getTargetObject(SpringTool.getBean(beanName)).getClass().getAnnotation(RequestMapping.class);
        if (requestMapping == null) {
            return null;
        }
        String tag = api.tags()[0];
        parentMap.put(beanName, tag);
        return tag;
    }

    /**
     * 处理一个资源
     * @param parentResourceDesc 父级资源描述
     * @param key
     * @param value
     */
    private void processResource(String parentResourceDesc, RequestMappingInfo key, HandlerMethod value) {
        String path = (String) key.getPatternsCondition().getPatterns().toArray()[0];

        boolean needInsert = false;

        // 按照 path 查询资源
        com.bjy.qa.entity.manage.Resource resource = lambdaQuery().eq(com.bjy.qa.entity.manage.Resource::getPath, path)
                .last("limit 1")
                .one();
        if (resource == null) {
            resource = new com.bjy.qa.entity.manage.Resource();
            needInsert = true;
        }

        resource.setPath(path); // 设置 path

        // 设置 desc
        ApiOperation apiOperation = value.getMethodAnnotation(ApiOperation.class);
        if (apiOperation == null) {
            resource.setDesc(parentResourceDesc + " - " + "未设置");
        }else {
            resource.setDesc(parentResourceDesc + " - " + apiOperation.value());
        }

        if (needInsert) {
            resourceDao.insert(resource);
        }else {
            resource.setUpdatedAt(null);
            resource.setCreatedAt(null);
            updateById(resource);
        }
    }
}
